import { create } from "zustand";
import * as apis from "@/apis/auth";

type Auth = ({ status: "ok" } & Me) | ({ status: "failed" | "loading" } & Partial<Me>);

type AuthActions = {
  load: () => void;
  login: (username: string, password: string) => Promise<{ ok: true } | { ok: false; message: string }>;
  logout: () => void;
};

const useAuthStore = create<Auth & AuthActions>()((set) => ({
  status: "loading",
  load: async () => {
    try {
      set({ status: "loading" });
      const me = await apis.profile();
      set({ status: "ok", ...me });
    } catch (err) {
      console.log("get profile failed", err);
      set({ status: "failed" });
    }
  },
  login: async (username: string, password: string) => {
    try {
      set({ status: "loading" });
      const me = await apis.login({ username, password });
      set({ status: "ok", ...me });
      return { ok: true };
    } catch (err) {
      set({ status: "failed" });
      return { ok: false, message: (err as Error).message };
    }
  },
  logout: async () => {
    await apis.logout();
    set({ status: "failed" });
  },
}));

export default useAuthStore;
